<template>
	<el-dialog
		v-model="dialogVisible"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
		:show-close="false"
		width="60%"
		align-center
		id="custom-dialog-map"
	>
		<template #header>
			<span class="text-xl">{{ type == 'point' ? '查看点位' : '打点' }}</span>
			<el-icon :size="24"><CircleClose class="cursor-pointer" @click="close" /></el-icon>
		</template>
		<div id="dialog-map" />
		<template #footer>
			<template v-if="type === 'dot'">
				<el-button type="primary" @click="dotFinish"> 确定 </el-button>
			</template>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { onUnmounted, onMounted, ref, nextTick } from 'vue';
import { ElDialog, ElButton, ElIcon, ElLoading, ElMessage } from 'element-plus';
import { CircleClose } from '@element-plus/icons-vue';
import { loadAmap } from '/@/utils/mapLoad';
import { getAddress } from '/@/utils/mapUtils';

const props = withDefaults(
	defineProps<{
		type: 'point' | 'dot';
		position: number[];
		dotSuccess: (val: { adcode: string; address: string; lng: number; lat: number }) => void;
	}>(),
	{
		position: () => [104.07, 30.57],
	}
);

// 地图记录始终让地图显示一个点标记
let marker: any;
let map: any;

onUnmounted(() => {
	if (map) {
		map = null;
		map.destroy();
	}
});
onMounted(() => {
	if (!map) initMap();
});

const dialogVisible = ref(true);

defineExpose({ open, close });

function open() {
	dialogVisible.value = true;
	initMap();
}
function close() {
	dialogVisible.value = false;
}

async function initMap() {
	await nextTick();
	// 加载地图
	await loadAmap();

	if (!map) {
		map = new window.AMap.Map('dialog-map');
		map.setCenter(props.position);
	}
	map.clearMap();

	// 查看点位
	if (props.type === 'point') {
		marker = new window.AMap.Marker({
			position: props.position,
		});

		map.add(marker);
		map.setFitView(marker);
		return;
	}

	// 打点
	map.on('click', async (e: any) => {
		const { lng, lat } = e.lnglat;

		marker = new window.AMap.Marker({
			position: [lng, lat],
		});

		map.add(marker);
	});
}

async function dotFinish() {
	if (!marker) {
		ElMessage.warning('请先打点');
		return;
	}
	const loadingInstance = ElLoading.service({
		lock: true,
		text: 'Loading',
		background: 'rgba(0, 0, 0, 0.7)',
	});
	const { lng, lat } = marker.getPosition();
	const address = await getAddress(lng, lat);
	props.dotSuccess({
		address: address.formattedAddress,
		adcode: address.addressComponent.adcode,
		lng,
		lat,
	});
	close();

	loadingInstance.close();
}
</script>

<style lang="scss">
#custom-dialog-map {
	.el-dialog__header {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.el-dialog__body {
		padding: 0 !important;
	}
}
</style>
<style scoped lang="scss">
#dialog-map {
	height: 500px;
}
</style>
